package com.acooly.module.openapi.client.provider.baofu;

import com.acooly.module.openapi.client.api.notify.ApiServiceClientServlet;
import com.acooly.module.openapi.client.api.transport.HttpTransport;
import com.acooly.module.openapi.client.api.transport.Transport;
import com.acooly.module.openapi.client.provider.baofu.enums.BaoFuServiceEnum;
import com.acooly.module.openapi.client.provider.baofu.notify.BaoFuApiServiceClientServlet;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

import java.util.List;

import static com.acooly.module.openapi.client.provider.baofu.OpenAPIClientBaoFuProperties.PREFIX;


@EnableConfigurationProperties({OpenAPIClientBaoFuProperties.class})
@ConditionalOnProperty(value = PREFIX + ".enable", matchIfMissing = true)
@ComponentScan
public class OpenAPIClientBaoFuConfigration {

    @Autowired
    private OpenAPIClientBaoFuProperties openAPIClientBaoFuProperties;

    @Bean("baoFuHttpTransport")
    public Transport BaoFuHttpTransport() {
        HttpTransport httpTransport = new HttpTransport();
        httpTransport.setGateway(openAPIClientBaoFuProperties.getGatewayUrl());
        httpTransport.setConnTimeout(String.valueOf(openAPIClientBaoFuProperties.getConnTimeout()));
        httpTransport.setReadTimeout(String.valueOf(openAPIClientBaoFuProperties.getReadTimeout()));
        return httpTransport;
    }

    /**
     * 宝付SDK-servlet注册
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean getApiSDKServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean();
        BaoFuApiServiceClientServlet apiServiceClientServlet = new BaoFuApiServiceClientServlet();
        bean.setServlet(apiServiceClientServlet);
        bean.addInitParameter(ApiServiceClientServlet.NOTIFY_DISPATCHER_BEAN_NAME_KEY, "baoFuNotifyHandlerDispatcher");
        List<String> urlMappings = Lists.newArrayList();       //网关异步通知地址
        urlMappings.add("/gateway/notify/baofuNotify/" + BaoFuServiceEnum.DEDUCT.getCode());//访问，可以添加多个
        urlMappings.add("/gateway/notify/baofuNotify/" + BaoFuServiceEnum.BATCH_DEDUCT.getCode());//访问，可以添加多个
        urlMappings.add("/gateway/notify/baofuNotify/" + BaoFuServiceEnum.REFUND.getCode());//访问，可以添加多个
        bean.setUrlMappings(urlMappings);
        bean.setLoadOnStartup(3);
        return bean;
    }
}
